/**
 * @author NORGUET Thibaud
 */
function init(){
    if (document.Virtools.CompositionLoaded == true) {
        _refreshChat();
    }
    else {
        setTimeout('init()', 1000);
    }
}

function V2JS_Message(_message){
    document.getElementById("upload_message").innerHTML += "Vmessage : " + _message + "<br />";
}

//fonction de sauvegarde des positions d'une cam qui viens d'etre mise sur l'environnement virtool
function V2JS_saveCamPosition(_position){
    var _tab = _position.split('!');
    
    V2JS_Message(_position);
    $.ajax({
        type: "POST",
        url: "./php/saveCamPosition.php",
        data: "position=" + _tab[0] + "&dir=" + _tab[1] + "&up=" + _tab[2] + "&id_user=" + _global_id_user,
        success: function(_msg){
            V2JS_Message("return getPos : " + _msg);
        }
    });
}


function V2JS_getCamPosition(){

    $.ajax({
        type: "POST",
        url: "./php/getCamPosition.php",
        success: function(){
            var cmd = "SendMessage 'Level' 'written' ";
            document.Virtools.DoCommand(cmd);
			V2JS_Message("return getPos : " + _msg);
        }
    });
}

function submitonEnter(evt,id_form){
	var _form = "form_"+id_form;
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode == "13") {
        _addChat(id_form);
    }
}

function V2JS_getCamInfo(_id_cam){
    $.getJSON("./php/getCamInfo.php", {
        "id_cam": _id_cam
    }, function(_json){
	var _html = '<div id="details">';
        _html += '<strong>Nom : </strong>  ' + _json['nom_user'] + '<br />';
        _html += '<strong>Partager cette cam:</strong> http://dev.citu.fr/lastlife/main.php?id=' + _id_cam + '<br />';
      	_html += '</div>';

		_html += '<div id="tag">';
		_html += 'Tag : <form onsubmit="_tag(' + _id_cam + '); return false;">';
		_html += '<input type="text" id="tagInput" size="15" />';
		_html += '<input type="submit" value="Tagguer" /></form></div>';

		_html += "<div id=favoris><input type='button' value='Ajouter aux favoris' onclick='_addfavoris(" + _id_cam + "); return false;' /></div>";

		_html += "<div class='commentsWrapper'>";
        _html += "<strong>Commentaires</strong> <br /><div id='_comment'></div><form action='' onsubmit='_addComment(" + _id_cam + "); return false;'>";
        _html += "<textarea rows='5' cols='62' id='commentaire' name='message'></textarea>";
        _html += "<br /><input type='submit' value='Valider' name='valid'></form>";
		_html += "</div>";

        _html += "Chat : <br /><div id='chat' style=border: 1px dashed black;'></div><form action='' onsubmit='_addChat(" + _id_cam + "); return false;'><textarea rows='2' cols='40' id='chat_post_" + _id_cam + "' onKeyDown='return submitonEnter(event,"+_id_cam+");'></textarea></br><input type='submit' value='Poster'></form>";
        
       	$('#camInfo').html(_html);
		// $.ui.dialog.defaults.bgiframe = true;
		// $("#camInfo").dialog();
    });
    _refreshComment(_id_cam, 0);
}

function V2JS_sendStat(_stat){
    var _tab = _stat.split('!');
    $.ajax({
        type: "POST",
        url: "./php/saveStat.php",
        data: "id_cam=" + _tab[0] + "&time=" + _tab[1] + "&sol=" + _tab[2],
        success: function(_msg){
            V2JS_Message(_msg);
        }
    });
}

function _goToCam(_id_user){
    var cmd = "SetAttribute '3dFrame_attribute' 'IDusers' '" + _id_user + "'";
    document.Virtools.DoCommand(cmd);
    cmd = "SendMessage 'Level' 'gotocam' ";
    document.Virtools.DoCommand(cmd);

}

function _addComment(_id_cam){
    var _comment = document.getElementById('commentaire').value;
    $.ajax({
        type: "POST",
        url: "./php/addComment.php",
        data: "id_cam=" + _id_cam + "&comment=" + _comment,
        success: function(_msg){
            V2JS_Message(_msg);
            document.getElementById('commentaire').value = "";
            _refreshComment(_id_cam, 0);
        }
    });
}

function _refreshComment(_id_cam, _pos){
    $.getJSON("./php/refreshComment.php", {
        "id_cam": _id_cam,
        "pos": _pos
    }, function(_json){
        var _html = "";
        for (var _i = 0; _i < _json["commentaire"].length; _i++) {
            _html += _json["commentaire"][_i];
        }
        _html += "<br />" + _json['prec'] + " " + _json['suiv'];
        $('#_comment').html(_html);
    });
}

function _addChat(_id_cam){

    var _message = document.getElementById('chat_post_' + _id_cam).value;
    $.ajax({
        type: "POST",
        url: "./php/addChat.php",
        data: "id_cam=" + _id_cam + "&message=" + _message,
        success: function(_msg){
            V2JS_Message(_msg);
            document.getElementById('chat_post_' + _id_cam).value = "";
        }
    });
}

function _refreshChat(){
    $.getJSON("./php/getChatUser.php", function(_json){
        // retourne les utilisateurs qui chat avec moi
        
        if (_json[0] != "") {
            var _html = "";
            var _compteur = 0;
            
            for (var _i = 0; _i < _json.length; _i++) {
                _compteur = 0;
                
                for (var _j = 0; _j <= _global_chat.length; _j++) {
                    if (_global_chat[_j] == _json[_i]) {
                    
                        _compteur = 1;
                    }
                }
                
                if (_compteur == 0) {
                    _global_chat.push(_json[_i]);
                    _html = '<div class="chat" id="chat_content_' + _global_chat[_global_chat.length - 1] + '"><img class="close" src="close.png" onclick="_close_chat(' + _global_chat[_global_chat.length - 1] + '); return false;" alt="fermer" title="fermer" /><div id="chat_' + _global_chat[_global_chat.length - 1] + '"></div>';
                    _html += "<form action='' onsubmit='_addChat(" + _global_chat[_global_chat.length - 1] + "); return false;'><textarea rows='2' cols='40' id='chat_post_" + _global_chat[_global_chat.length - 1] + "' onKeyDown='return submitonEnter(event,"+_global_chat[_global_chat.length - 1]+");'></textarea></br>";
                    _html += "<input type='submit' value='Poster'></form></div>";
                    document.getElementById('div_chat').innerHTML += _html;
                }
            }
            for (var _i = 0; _i < _global_chat.length; _i++) { //pour chaque user on refresh 
                $.getJSON("./php/refreshChat.php", {
                    "id_cam": _global_chat[_i]
                }, function(_json){
                    var _div = "chat_" + _json[0];
                    
                    var _html = "";
                    for (var _j = 1; _j < _json[1].length; _j++) {
                        _html += _json[1][_j];
                    }
                    $('#' + _div).html(_html);
                });
            }
        }
        else {
            V2JS_Message('pas de chat');
        }
        
    });
    
    setTimeout('_refreshChat()', 1000);
}

function _removeWho(who){
    if (typeof who == 'string') 
        who = document.getElementById(who);
    if (who && who.parentNode) 
        who.parentNode.removeChild(who);
}



function _close_chat(_id_chat){
    // doit supprimer la personne du tableau global js et de la bdd et supprimer les conversation entre les deux de la bdd !
    $.ajax({
        type: "POST",
        url: "./php/deleteChat.php",
        data: "id_chat=" + _id_chat,
        success: function(_msg){
            V2JS_Message(_msg);
        }
    });
    
    var _tmp_tab = new Array();
    var _i = 0;
    for (_i; _i < _global_chat.length; _i++) {
        if (_global_chat[_i] != _id_chat) {
            _tmp_tab.push(_global_chat[_i]);
        }
    }
    _global_chat = new Array();
    for (_i = 0; _i < _tmp_tab.length; _i++) {
        _global_chat.push(_tmp_tab[_i]);
    }
    _removeWho("chat_content_" + _id_chat);
    
}

function JS2V_logout(){
    var cmd = "SendMessage 'Level' 'logout' ";
    document.Virtools.DoCommand(cmd);
}

function V2JS_lastPosition(_position){
    var _tab = _position.split('!');
    V2JS_Message(_position);
    $.ajax({
        type: "POST",
        url: "./php/saveLastPosition.php",
        data: "position=" + _tab[0] + "&dir=" + _tab[1] + "&up=" + _tab[2] + "&id_user=" + _global_id_user,
        success: function(_msg){
            V2JS_Message("return getPos : " + _msg);
        }
    });
}


function JS2V_login(){
    var cmd = "SendMessage 'Level' 'login' ";
    document.Virtools.DoCommand(cmd);
    
    $.getJSON("./php/getStartPosition.php", {
        "id_user": _global_id_user
    }, function(_json){
        var _position = _json['latitude'] + ":" + _json['altitude'] + ":" + _json['longitude'];
        
        var cmd = "SetAttribute '3dFrame_attribute' 'positionCamera' '" + _position + "'";
        document.Virtools.DoCommand(cmd);
        cmd = "SetAttribute '3dFrame_attribute' 'orientationDir' '" + _json['orientation_dir'] + "'";
        document.Virtools.DoCommand(cmd);
        cmd = "SetAttribute '3dFrame_attribute' 'orientationUp' '" + _json['orientation_up'] + "'";
        document.Virtools.DoCommand(cmd);
        V2JS_Message("pos : " + _position);
        V2JS_Message("orientation_dir : " + _json['orientation_dir']);
        V2JS_Message("orientation_up : " + _json['orientation_up']);
        
    });
    V2JS_getCamPosition();
}


function _identification(_login){

    $.getJSON("./php/identification.php", {
        "login": _login
    }, function(_json){
    
        if (_json != "") {
            var v_html = "";
            
            _global_id_user = _json['id_user'];
            setTimeout("JS2V_login()", 3000);
            
        }
        else {
            document.getElementById("content").innerHTML += "<br /> Erreur d'identification";
        }
        
        
    });
}



function f_sendPassMail(){
    var _email = document.getElementById('email').value;
    $.ajax({
        type: "POST",
        url: "./php/sendPassMail.php",
        data: "email=" + _email,
        success: function(_msg){
            //document.location.replace("http://dev.citu.fr/lastlife/");
            document.getElementById('id_mail').innerHTML += _msg;
        }
    });
}



function f_verif_form(nom_input){

    if (document.getElementById(nom_input).value == "") {
        document.getElementById(nom_input).style.backgroundColor = "#F99";
    }
    else {
        document.getElementById(nom_input).style.backgroundColor = "white";
    }
}

function f_save_compte(){

    var tab = new Array;
    var _login = $("#login").val();
    var _pass = $("#pass").val();
    var _mail = $("#mail").val();
    
    
    if (document.getElementById("login").value == "") {
        tab.push("x");
        document.getElementById("login").style.backgroundColor = "#F99";
    }
    if (document.getElementById("pass").value == "") {
        tab.push("x");
        document.getElementById("pass").style.backgroundColor = "#F99";
    }
    if (document.getElementById("mail").value == "") {
        tab.push("x");
        document.getElementById("mail").style.backgroundColor = "#F99";
    }
    
    if (tab.length == 0) {
        $.ajax({
            type: "POST",
            url: "./php/saveCompte.php",
            data: "login=" + _login + "&pass=" + _pass + "&mail=" + _mail,
            success: function(_msg){
            
                document.getElementById("new_compte").innerHTML += "<br />" + _msg;
            }
        });
    }
    else {
        return false;
        
    }
    
}

function changeVitesse(_speed){
    var cmd = "SetAttribute '3dFrame_attribute' 'vitesse' '" + _speed + "'";
    document.Virtools.DoCommand(cmd);
    if (_speed == 20) {
        var _html = '<input type="button" onclick="changeVitesse(2);" value="x2" />';
    }
    else {
        var _html = '<input type="button" onclick="changeVitesse(20);" value="x20" />';
    }
    $("#vitesse").html(_html);
}

function _tag(_id_cam){
    var _tag = document.getElementById('tagInput').value;
    $.ajax({
        type: "POST",
        url: "./php/saveTag.php",
        data: "tag=" + _tag + "&id_cam=" + _id_cam,
        success: function(_msg){
            V2JS_Message(_msg);
        }
    });
}

function _getUserTag(_id_user){
    if (_id_user != "") {
        $.getJSON("./php/getUserTag.php", {
            "id": _id_user
        }, function(_json){
            var _html = "";
            /*var _html = "<table>";
             for (var indice in _json) {
             _html += "<tr><td>" + indice + " : </td><td>" + _json[indice] + "</td></tr>";
             }*/
            for (var _i = 0; _i < _json.length; _i++) {
                _html += _json[_i]['keyword'] + " (" + _json[_i]['tag_occurence'] + ") <br />";
            }
            $('.cloud').html(_html);
        });
    }
}

function _searchTag(){
    var _tag = document.getElementById('searchTag').value;
    $.getJSON("./php/searchTag.php", {
        "tag": _tag
    }, function(_json){
        var _html = "";
        if (_json.length == 0) {
            _html = "Tag inexistant.";
        }
        else {
            /*var _html = "<table>";
             for (var indice in _json) {
             _html += "<tr><td>" + indice + " : </td><td>" + _json[indice] + "</td></tr>";
             }*/
            for (var _i = 0; _i < _json.length; _i++) {
                _html += "<a href='' onclick='_goToCam(" + _json[_i]['id_user'] + "); return false;'>" + _json[_i]['login'] + " (" + _json[_i]['tag_occurence'] + ")</a> <br />";
            }
        }
        $('#tagcloud').html(_html);
    });
    
}

function _addfavoris(_id_cam){
    $.ajax({
        type: "POST",
        url: "./php/addFavoris.php",
        data: "id_cam=" + _id_cam,
        success: function(_msg){
            V2JS_Message(_msg);
        }
    });
}
